<template>
    <div class="page animate__animated animate__fadeIn">
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '20px 20px' }">
            <el-page-header @back="goBack" :content="showEditBtn ? '发货订单详情' : '订单详情'"></el-page-header>
        </el-card>
        <el-card v-if="orderDetail.status == 10 && showEditBtn" :bordered="false" shadow="never" class="ivu-mt"
            :body-style="{ padding: '10px 20px 0' }" v-loading="loadingPage">
            <div class="goods-info-t">
                <h2 class="el-descriptions__title">{{ isdriver ? '修改司机' : '指派司机' }}</h2>
            </div>
            <el-form size="small" :model="ruleForm" ref="ruleForm" inline label-position="right">
                <el-form-item label="选择地址" prop="supply_address_id">
                    <el-select v-model="ruleForm.supply_address_id" placeholder="请选择地址">
                        <el-option v-for="item in address" :key="item.supply_address_id" :label="item.address_detail"
                            :value="item.supply_address_id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选择司机" prop="driver_id">
                    <el-select v-model="ruleForm.driver_id" placeholder="请选择司机">
                        <el-option v-for="item in driver" :key="item.driver_id" :label="item.contact"
                            :value="item.driver_id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="btn" size="small" @click="judgementVocher" :disabled="isDisabled"
                        :loading="isLoading">确 定</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '0px 20px' }"
            v-loading="loadingPage">
            <template v-if="showPage">
                <el-descriptions title="订单信息">
                    <el-descriptions-item label="订单状态">
                        <template v-if="orderDetail.status == 10">
                            <el-tag size="small">{{
                                orderDetail.state_text }}<i class="el-icon-right"></i>{{
                                    orderDetail.driver_id > 0 ? '修改指派司机' : '指派司机' }}</el-tag>
                        </template>
                        <el-tag size="small" v-else>{{ orderDetail.state_text }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单编号">{{ orderDetail.orderM.order_no }}<em class="copy"
                            @click="copyEv(orderDetail.orderM.order_no)">复制</em></el-descriptions-item>
                    <el-descriptions-item label="包裹编号">#{{ orderDetail.supply_order_no }}</el-descriptions-item>
                    <el-descriptions-item label="下单来源">
                        <el-tag type="success" size="small" v-if="orderDetail.orderM.platform == 1">小程序</el-tag>
                        <el-tag type="success" size="small" v-if="orderDetail.orderM.platform == 2">PC</el-tag>
                        <el-tag type="success" size="small" v-if="orderDetail.orderM.platform == 3">平台</el-tag>
                        <el-tag type="success" size="small" v-if="orderDetail.orderM.platform == 4">分公司</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="手续费">￥{{ orderDetail.supply_goods_service }}</el-descriptions-item>
                    <el-descriptions-item label="合计金额">￥{{ orderDetail.supply_total_price }}</el-descriptions-item>
                    <el-descriptions-item label="支付方式">线下支付</el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{ orderDetail.create_time }}</el-descriptions-item>
                    <el-descriptions-item label="下单时间" v-if="orderDetail.status == 30">{{ orderDetail.received_time
                        }}</el-descriptions-item>
                    <!-- <el-descriptions-item label="送达凭证"
                        v-if="orderDetail.status == 20 && orderDetail.review_delivery == 10">
                        <el-tag type="success" style="cursor: pointer;" size="small" v-if="orderDetail.delivery_voucher"
                            @click="ImgVisible = true">查看</el-tag>
                        <el-tag type="info" size="small" v-else>暂无</el-tag>
                    </el-descriptions-item> -->
                    <el-descriptions-item label="送达凭证">
                        <template>
                            <div v-if="orderDetail.delivery_voucher" style="cursor: pointer;" @click="previewImg">
                                <el-image :src="orderDetail.delivery_voucher" fit="contain" class="list-img">
                                    <div slot="error" class="image-slot">
                                        <p>暂无图片</p>
                                    </div>
                                </el-image>
                            </div>
                            <el-tag size="mini" type="info" v-else class="ml">暂无</el-tag>
                        </template>
                    </el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="收货信息">
                    <el-descriptions-item label="收货人">{{ orderDetail.address.name }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ orderDetail.address.phone }}<em class="copy"
                            @click="copyEv(orderDetail.address.phone)">复制</em></el-descriptions-item>
                    <el-descriptions-item label="收货地址">{{ orderDetail.address.address_detail }}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="发货信息" v-if="orderDetail.supply_address_id > 0">
                    <el-descriptions-item label="联系人">{{ orderDetail.supplyAddress.name }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ orderDetail.supplyAddress.phone }}<em class="copy"
                            @click="copyEv(orderDetail.supplyAddress.phone)">复制</em></el-descriptions-item>
                    <el-descriptions-item label="地址">{{ orderDetail.supplyAddress.address_detail
                        }}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="司机信息" v-if="orderDetail.driver_id > 0">
                    <el-descriptions-item label="配送员">{{ orderDetail.driver.contact }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ orderDetail.driver.phone }}<em class="copy"
                            @click="copyEv(orderDetail.driver.phone)">复制</em></el-descriptions-item>
                    <el-descriptions-item label="车牌号">{{ orderDetail.driver.car_no }}</el-descriptions-item>
                </el-descriptions>
                <div class="goods-info" v-if="orderDetail.status == 20">
                    <div class="goods-info-t">
                        <h2 class="el-descriptions__title">司机位置</h2>
                    </div>
                    <div class="map-con" v-if="orderDetail.status == 20">
                        <div id="yzMap"></div>
                        <!-- <baidu-map class="bm-view" :zoom="zoom" @ready="handler" :center="center" :scroll-wheel-zoom="true"
                                   :ak="mapKey">
                            <template v-if="showMap">
                                <bm-marker v-for="(marker,index) in mapData.markers" :key="index" :position="{lng: marker.lng, lat: marker.lat}">
                                    <bm-label :content="marker.label" :labelStyle="labelStyle" @ready="logItemWidths"
                                              :offset="{width:-offsetArr[index],height:30}" />
                                </bm-marker>
                            </template>
</baidu-map> -->
                    </div>
                </div>
                <div class="goods-info">
                    <div class="goods-info-t">
                        <h2 class="el-descriptions__title">商品信息</h2>
                    </div>
                    <div class="package-wrap">
                        <el-table size="small" border header-cell-class-name="table_header_cell"
                            :data="orderDetail.orderSupplyGoods">
                            <el-table-column prop="goods_id" label="商品ID">
                                <template slot-scope="scope">
                                    <span>{{ scope.row.order_goods_item.goods_id }}</span>
                                    <el-tag size="mini" type="success"
                                        v-if="scope.row.order_goods_item.goods_type == 10">自营</el-tag>
                                    <el-tag size="mini" type="danger" v-else>供货商</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="商品图片">
                                <template slot-scope="scope">
                                    <el-image :src="scope.row.order_goods_item.goods_image" fit="contain"
                                        class="list-img">
                                        <div slot="error" class="image-slot">
                                            <p>暂无图片</p>
                                        </div>
                                    </el-image>
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_name" label="商品名称" width="300px">
                                <template slot-scope="scope">
                                    {{ scope.row.order_goods_item.goods_name }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="sku_name" label="商品规格">
                                <template slot-scope="scope">
                                    {{ scope.row.order_goods_item.sku_name }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_price" label="商品金额" align="right">
                                <template slot-scope="scope">
                                    <div class="goods-price-info">
                                        <p>单价：￥{{ scope.row.supply_price }}<i
                                                v-if='scope.row.order_goods_item.goods_unit'>/{{
                                                    scope.row.order_goods_item.goods_unit }}</i></p>
                                        <p>数量：x{{ scope.row.order_goods_item.total_num }}</p>
                                        <p>小计：{{ scope.row.supply_order_price }}</p>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_price" label="手续费" align="right">
                                <template slot-scope="scope">
                                    <div class="goods-price-info">
                                        <p>费率：{{ scope.row.goods_agent_rate }}%</p>
                                        <p>费用：{{ scope.row.goods_service_price }}元</p>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_price" label="食品安全信息" align="right">
                                <template slot-scope="scope">
                                    <div class="goods-price-info" v-if="scope.row.order_goods_item.qs_food">
                                        <p>
                                            <el-image :src="scope.row.order_goods_item.qs_food" fit="contain"
                                                class="list-img" :preview-src-list="qsList">
                                                <div slot="error" class="image-slot">
                                                    <p>暂无图片</p>
                                                </div>
                                            </el-image>
                                            <el-button type="text" v-if="showEditBtn"
                                                @click="toEdit(scope.row.order_goods_item, scope.$index)"><i
                                                    class="el-icon-upload" style="font-size: 20px;"></i></el-button>
                                        </p>

                                        <p>信息：{{ scope.row.order_goods_item.qs_info }}</p>
                                    </div>
                                    <div class="goods-price-info" v-else>
                                        <el-button v-if="showEditBtn" type="success" plain size="mini"
                                            @click="toUpload(scope.row.order_goods_item.order_goods_id, scope.$index)">去上传</el-button>
                                        <p v-else>暂无</p>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </template>
        </el-card>
        <food-security ref='food' @reload="updateFood"></food-security>
        <!-- <assign-driver ref="assign" @reload="getOrderDetail"></assign-driver> -->
        <template v-if="ImgVisible">
            <preview-image style="z-index: 999;" :ImgVisible="ImgVisible" @close="ImgVisible = false"
                :imgSrc="orderDetail.delivery_voucher"></preview-image>
        </template>
    </div>
</template>
<script>
import { orderDetailApi, orderDelivery, checkOrderItemVocher } from '../../api/order';
import { getSettingByKey, addrList } from '../../api/setting';
import { driverData } from '../../api/driver';
import FoodSecurity from './components/FoodSecurity.vue';
import PreviewImage from '@/components/previewImage.vue';
// import { BaiduMap } from 'vue-baidu-map';
// import BmMarker from 'vue-baidu-map/components/overlays/Marker.vue';
// import BmLabel from 'vue-baidu-map/components/overlays/Label.vue';
export default {
    components: { FoodSecurity, PreviewImage },
    // components: { BaiduMap, BmMarker, BmLabel },
    data() {
        return {
            loadingPage: true,
            showPage: false,
            orderDetail: {},
            orderId: "",
            visible: false,
            mapData: {},
            zoom: 0,
            center: '',
            labelStyle: {
                color: '#333',
                fontSize: '12px',
                border: 0,
                padding: "6px 10px",
                borderRadius: '4px',
                boxShadow: '0 6px 12px 2px rgba(0, 0, 0, 0.3)'
            },
            offsetArr: [],
            showMap: false,
            mapMarkerIcon: require('@/assets/img/circle.png'),
            qsList: [],
            orderGoodsIndex: -1,
            ImgVisible: false, // 查看送达凭证
            imgUrl: '', // 凭证路径
            // 指派司机表单
            ruleForm: {
                supply_order_id: "",
                driver_id: "",
                supply_address_id: "",
            },
            // 司机地址列表
            address: [],
            // 司机列表
            driver: [],
            isDisabled: false,
            isLoading: false,
        }
    },
    computed: {
        mapKey() {
            return this.$store.state.baiduMapKey;
        },
        /**
         * 是否指派了司机
         * true 是
         * false 否
         */
        isdriver() {
            return this.orderDetail.driver_id > 0
        },
        // 0 查看详情 1 编辑
        showEditBtn() {
            return this.$route.query.type == '1'
        }
    },
    created() {
        this.orderId = this.$route.query.id ? this.$route.query.id : "";
        this.getOrderDetail();
        this.loadTDTjsOnCurrentPage()
    },
    methods: {
        previewImg() {
            const { delivery_voucher } = this.orderDetail
            this.imgUrl = delivery_voucher;
            this.ImgVisible = true;
        },
        // 判断是否上传了食品安全证书
        judgementVocher() {
            this.isDisabled = true;
            this.isLoading = true;
            checkOrderItemVocher({
                supply_order_id: this.orderId
            }).then(res => {
                if (res.code == 0) {
                    this.toAssign()
                } else {
                    this.isDisabled = false;
                    this.isLoading = false;
                }
            })
        },
        // 确定指派司机
        async toAssign() {
            this.ruleForm.supply_order_id = this.orderId
            let res = await this.$getCsrToken();
            orderDelivery(this.ruleForm).then((res) => {
                if (res.code == 0) {
                    this.$message({
                        message: res.msg,
                        type: "success",
                    });
                    this.isDisabled = false;
                    this.isLoading = false;
                    this.getOrderDetail()
                } else {
                    this.isDisabled = false;
                    this.isLoading = false;
                }
            });
        },
        // 获取司机列表
        getDriverList() {
            driverData().then(res => {
                if (res.code == 0) {
                    this.driver = res.data;
                }
            })
        },
        // 获取地址列表
        getAddressList() {
            addrList().then(res => {
                if (res.code == 0) {
                    this.address = res.data;
                }
            })
        },
        getOrderDetail() {
            const that = this;
            that.loadingPage = true;
            that.showPage = false;
            orderDetailApi({
                supply_order_id: that.orderId,
            }).then(res => {
                that.loadingPage = false;
                that.showPage = true;
                if (res.code == 0) {
                    that.orderDetail = res.data;
                    // 10 待发货
                    if (that.orderDetail.status == 10) {
                        that.getAddressList()
                        that.getDriverList()
                    }
                    var qsList = res.data.orderSupplyGoods.filter(v => {
                        return v.order_goods_item.qs_food != null
                    })
                    that.qsList = qsList.map(v => {
                        return v.order_goods_item.qs_food
                    })
                    // console.log('that.qsList', that.qsList)
                    that.updateMapData()
                }
            })
        },
        loadTDTjsOnCurrentPage() {
            getSettingByKey({
                keys: 'tencent'
            }).then(res => {
                if (res.code == 0) {
                    let script = document.createElement('script');
                    script.type = 'text/javascript'
                    script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${res.data.values.map_customer_key}`
                    document.body.appendChild(script)
                }
            })
        },
        initMap() {
            const that = this;
            var T = window.T;
            this.map = new T.Map('yzMap');
            this.map.centerAndZoom(new T.LngLat(this.mapData.markers[1].lng, this.mapData.markers[1].lat), 12);
            console.log('this.mapData', this.mapData)
            this.mapData.markers.forEach((v, i) => {
                const point = new T.LngLat(v.lng, v.lat);
                const icon = new T.Icon({
                    iconUrl: that.mapMarkerIcon,
                    iconSize: new T.Point(15, 15),
                });
                const marker = new T.Marker(point, {
                    icon: icon
                })
                this.map.addOverLay(marker);
                let label = new T.Label({
                    text: v.label,
                    position: point,
                })
                this.map.addOverLay(label);
                label.setOffset(new T.Point(-(label._labelWidth / 2 + 8), 26))
            })
        },
        updateMapData() {
            const orderDetail = this.orderDetail;
            if (orderDetail.status == 20) {
                const userAddress = {
                    id: 1,
                    lng: orderDetail.address.lng,
                    lat: orderDetail.address.lat,
                    label: orderDetail.address.detail
                }
                const supplyAddress = {
                    id: 3,
                    lng: orderDetail.supplyAddress.lng,
                    lat: orderDetail.supplyAddress.lat,
                    label: orderDetail.supplyAddress.detail
                }
                const centerAddress = {
                    id: 2,
                    lng: (parseFloat(userAddress.lng) + parseFloat(supplyAddress.lng)) / 2,
                    lat: (parseFloat(userAddress.lat) + parseFloat(supplyAddress.lat)) / 2,
                    label: '司机位置'
                }
                this.mapData = {
                    markers: [userAddress, centerAddress, supplyAddress],
                };
                setTimeout(() => {
                    this.initMap()
                }, 600)
            }
        },
        handler({ BMap, map }) {
            var view = map.getViewport(eval(this.mapData.markers))
            this.zoom = view.zoom;
            this.center = view.center;
            setTimeout(() => {
                this.logItemWidths()
            }, 500)
        },
        logItemWidths() {
            this.$nextTick(() => {
                const elements = document.getElementsByClassName("BMapLabel");
                let elementsWidthArr = []
                for (var i = 0; i < elements.length; i++) {
                    const element = elements[i];
                    const elementW = element.offsetWidth;
                    const elementCenterW = elementW / 2 - 8;
                    elementsWidthArr.push(elementCenterW)
                }
                elementsWidthArr.shift();
                this.offsetArr = elementsWidthArr;
            });
        },
        copyEv(mobile) {
            navigator.clipboard
                .writeText(mobile)
                .then(() => {
                    this.$message.success("复制成功");
                })
                .catch((err) => {
                    // 复制失败
                    console.error("复制失败");
                });
        },
        toUpload(order_goods_id, index) {
            this.orderGoodsIndex = index;
            this.$refs.food.ruleForm.order_id = this.orderDetail.orderM.order_id;
            this.$refs.food.ruleForm.order_goods_id = order_goods_id;
            this.$refs.food.add()
        },
        toEdit(goods, index) {
            this.orderGoodsIndex = index;
            this.$refs.food.ruleForm.order_id = this.orderDetail.orderM.order_id;
            this.$refs.food.ruleForm.order_goods_id = goods.order_goods_id;
            this.$refs.food.ruleForm.qs_food = goods.qs_food;
            this.$refs.food.ruleForm.qs_info = goods.qs_info;
            this.$refs.food.isEdit = true;
            // console.log('this.$refs.food.ruleForm', this.$refs.food.ruleForm)
            this.$refs.food.add()
        },
        updateFood(obj) {
            const orderDetail = this.orderDetail;
            const index = this.orderGoodsIndex;
            console.log('obj', obj)
            orderDetail.orderSupplyGoods[index].order_goods_item.qs_food = obj.qs_food;
            orderDetail.orderSupplyGoods[index].order_goods_item.qs_info = obj.qs_info;
            this.orderDetail = orderDetail;
            console.log('this.orderDetail', this.orderDetail)
        },
        // assignDriver() {
        //     const orderGoods = this.orderDetail.orderSupplyGoods;
        //     var foodFlag = orderGoods.every(function (a, b, c) {
        //         return a.order_goods_item.qs_food != null;
        //     })
        //     if (!foodFlag) {
        //         this.$message.error('请上传食品安全信息！')
        //         return;
        //     }
        //     this.$refs.assign.show();
        //     this.$refs.assign.ruleForm.supply_order_id = this.orderId;
        // },
        goBack() {
            this.$router.go(-1);
        },
    }
}
</script>
<style scoped>
/deep/ .el-descriptions {
    padding: 15px 0 0px;
    border-bottom: 1px dashed #dcdfe6;
}

/deep/ .el-descriptions__header {
    margin-bottom: 15px;
}

/deep/ .el-descriptions__title {
    position: relative;
    padding-left: 8px;
    font-size: 14px;
}

/deep/ .el-descriptions__title:before {
    content: "";
    width: 3px;
    height: 16px;
    border-radius: 4px;
    background: var(--main-color);
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

/deep/ .el-divider__text {
    font-weight: bold;
}

.table-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
}

.btn-wrap {
    width: 100px;
    height: inherit;
    /* background: red; */
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 20px;
}

.goods-info {
    padding: 15px 0;
    border-bottom: 0;
}

.goods-info-t {
    display: flex;
}

.goods-info-t h2 {
    line-height: 32px;
    margin-right: 12px;
}

.goods-price-info span {
    text-align: right;
}

.supply-info li {
    display: flex;
}

.supply-info li span {}

.ml {
    margin-left: 10px;
}

.copy {
    color: var(--main-color);
    font-style: normal;
    padding-left: 10px;
    cursor: pointer;
}

.map-con {
    margin-top: 20px;
}

#yzMap {
    width: 100%;
    height: 428px;
    border-radius: 8px;
    overflow: hidden;
}
</style>